package org.example.steamshop.controller;

import javax.servlet.http.HttpSession;

import org.example.steamshop.service.OrderService;
import org.example.steamshop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @GetMapping("/orders")

    public String orders(Model model, HttpSession session) {
        Long userId = (Long) session.getAttribute("userId");
        if (userId == null) {
            return "redirect:/login";
        }

        model.addAttribute("orders", orderService.getUserOrders(userId));
        return "orders";
    }

    @PostMapping("/order/create")
    public String createOrder(HttpSession session) {
        Long userId = (Long) session.getAttribute("userId");
        if (userId == null) {
            return "redirect:/login";
        }

        orderService.createOrder(userId);
        return "redirect:/orders";
    }

    @PostMapping("/order/delete")
    public String deleteOrder(@RequestParam("orderId") Long orderId,
                              HttpSession session,
                              RedirectAttributes redirectAttributes) {
        Long userId = (Long) session.getAttribute("userId");
        if (userId == null) {
            return "redirect:/login";
        }

        try {
            boolean isDeleted = orderService.deleteOrder(orderId, userId);
            if (isDeleted) {
                redirectAttributes.addFlashAttribute("successMessage", "订单删除成功！");
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "订单不存在或您无权删除此订单");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "删除订单时出错: " + e.getMessage());
        }
        return "redirect:/orders";
    }



}